using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using UpdaterManagement.Data;
using UpdaterManagement.Models;
using Microsoft.AspNetCore.Authorization;

namespace UpdaterManagement.Controllers
{
    [Authorize]
    public class DeployedApplicationController : Controller
    {
        private readonly ApplicationDbContext _context;

        public DeployedApplicationController(ApplicationDbContext context)
        {
            _context = context;
        }

        public async Task<IActionResult> Index(int? productId, int? enterpriseId, int page = 1, int pageSize = 5)
        {
            var query = _context.DeployedApplications
                .Include(a => a.Enterprise)
                .Include(a => a.Product)
                .AsQueryable();
            
            if (productId.HasValue)
            {
                query = query.Where(a => a.ProductId == productId.Value);
            }
            
            if (enterpriseId.HasValue)
            {
                query = query.Where(a => a.EnterpriseId == enterpriseId.Value);
            }
            
            var totalCount = await query.CountAsync();
            var applications = await query
                .OrderByDescending(a => a.CreatedTime)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();
            
            ViewBag.ProductId = productId;
            ViewBag.EnterpriseId = enterpriseId;
            ViewBag.Products = await _context.Products.ToListAsync();
            ViewBag.Enterprises = await _context.Enterprises.Where(e => e.IsActive).ToListAsync();
            ViewBag.CurrentPage = page;
            ViewBag.PageSize = pageSize;
            ViewBag.TotalCount = totalCount;
            ViewBag.TotalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            
            return View(applications);
        }

        public async Task<IActionResult> Create()
        {
            ViewBag.Enterprises = await _context.Enterprises.Where(e => e.IsActive).ToListAsync();
            ViewBag.Products = await _context.Products.ToListAsync();
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Create(DeployedApplication model)
        {
            if (ModelState.IsValid)
            {
                _context.DeployedApplications.Add(model);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

        public async Task<IActionResult> Edit(int id)
        {
            var application = await _context.DeployedApplications.FindAsync(id);
            if (application == null) return NotFound();
            ViewBag.Enterprises = await _context.Enterprises.Where(e => e.IsActive).ToListAsync();
            ViewBag.Products = await _context.Products.ToListAsync();
            return View(application);
        }

        [HttpPost]
        public async Task<IActionResult> Edit(DeployedApplication model)
        {
            if (ModelState.IsValid)
            {
                model.LastUpdated = DateTime.Now;
                _context.DeployedApplications.Update(model);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            var application = await _context.DeployedApplications.FindAsync(id);
            if (application != null)
            {
                _context.DeployedApplications.Remove(application);
                await _context.SaveChangesAsync();
            }
            return RedirectToAction(nameof(Index));
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> GetByEnterprise(int enterpriseId)
        {
            var applications = await _context.DeployedApplications
                .Where(a => a.EnterpriseId == enterpriseId && a.IsActive)
                .ToListAsync();
            return Json(applications);
        }
    }
}